import React, { useEffect, useState, useMemo } from "react";
import { Typography, message, Tree } from "antd";

import EditNameModal from "./EditNameModal";
import EditResourceModal from "./EditResourceModal";
import request from "@/utils/request";
import { transformTreeData } from "@/utils/util";
import { roleTypeTextMap } from "@/utils/consts";
import { useAppSelector } from "@/utils/hooks";

import type { RecordDetail } from "../type";

interface Props {
	roleId?: React.Key;
	onEdit: (detail: RecordDetail) => void;
}

const Content: React.FC<Props> = ({ roleId, onEdit }) => {
	const [app] = useAppSelector(state => [state.app]);
	const [detail, setDetail] = useState<RecordDetail>();

	useEffect(() => {
		if (roleId) {
			queryDetail();
		}
	}, [roleId]);

	const queryDetail = () => {
		request("roleManageRoleDetail", {
			data: {
				roleId: roleId,
				tenantId: app.currentEntity?.entityId
			}
		}).then(res => {
			if (res.code === 0) {
				setDetail(res.data);
			}
		});
	};

	const handleEdit = (values: RecordDetail) => {
		return request("roleManageEdit", {
			data: {
				...values,
				roleId: detail?.roleId,
				tenantId: app.currentEntity?.entityId
			}
		}).then(res => {
			if (res.code === 0) {
				message.success("修改成功");
				onEdit({ ...detail, ...values } as RecordDetail);
				queryDetail();
			}
			return res;
		});
	};

	const resourceTree = useMemo(() => {
		return detail?.resourceList || [];
	}, [detail]);

	const items = useMemo(() => {
		return [
			{
				label: "角色类型",
				content: roleTypeTextMap[detail?.roleType as keyof typeof roleTypeTextMap]
			},
			{
				label: "角色名称",
				content: detail?.roleName,
				editor: detail?.roleName && <EditNameModal onEdit={handleEdit} detail={detail}></EditNameModal>
			},
			{
				label: "资源点权限",
				content: !!resourceTree.length && (
					<Tree defaultExpandAll selectable={false} key={detail?.roleId} treeData={resourceTree}></Tree>
				),
				editor: (
					!!resourceTree.length &&  <EditResourceModal
						detail={detail}
						editText="设置"
						onEdit={handleEdit}
					></EditResourceModal>
				)
			}
		];
	}, [detail, resourceTree]);

	return (
		<div className="role-manage-content flex1">
			<Typography.Title level={5} style={{ margin: 0 }}>
				角色信息
			</Typography.Title>
			{items.map((item, index) => {
				return (
					<div className="startCenter content-item" key={index}>
						<div className="label">{item.label}</div>
						<div className="flex1 startCenter value" style={{ borderBottom: index === items.length - 1 ? 0 : "" }}>
							<div className="flex1">{item.content}</div>
							{item.editor && item.editor}
						</div>
					</div>
				);
			})}
		</div>
	);
};

export default Content;
